/*
 * @lc app=leetcode.cn id=102 lang=cpp
 *
 * [102] 二叉树的层序遍历
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
   public:
    vector<vector<int>> levelOrder(TreeNode *root) {
        queue<TreeNode *> nodeQueue;  // 记录待访问的节点的队列
        vector<int> layer;            // 记录每一层的节点值
        vector<vector<int>> result;   // 记录整棵树的节点值

        // 特判 root 为空，直接返回
        if (root == nullptr) return result;     

        nodeQueue.push(root);
        while (!nodeQueue.empty()) {
            // 遍历该层的所有元素
            int length = nodeQueue.size();
            for (int i = 0; i < length; i++) {
                TreeNode* node = nodeQueue.front();
                nodeQueue.pop();

                layer.push_back(node->val);

                if (node->left != nullptr) nodeQueue.push(node->left);       
                if (node->right != nullptr) nodeQueue.push(node->right);                
            }
            // 将该层的结果保存至整棵树
            result.push_back(layer);
            layer.clear();
        }

        return result;
    }
};
// @lc code=end
